package m3d29;
//同步代码块
//锁对象可是任意对象,多线程的所对象是同一个
//作用：把代码锁住，只让一个线程执行

/*同步方法
* 把实现类的对象锁住*/

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class mRunnable implements Runnable{
    private int ticket = 100;

    //创建锁对象
/*    Object object = new Object();

    @Override
    public void run() {
        while(true) {
           //同步代码块
            synchronized (object){

            if (ticket > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("票数为" + ticket);
                ticket--;
            }
        }
        }
    }*/

    /* 同步方法 */
/*    @Override
    public void run() {
        while(true) {
            payTickey();
        }
    }

    public synchronized void payTickey(){

            if (ticket > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("票数为" + ticket);
                ticket--;
            }
        }*/

    //lock锁
    //1.在成员位置创建对象  lock接口
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            //2安全问题代码前调用lock方法获取锁
            lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("票数为" + ticket);
                    ticket--;
                }
            //3安全问题代码后调用lock方法释放锁
            lock.unlock();
            }
        }


    public int getTicket() {
        return ticket;
    }

    public void setTicket(int ticket) {
        this.ticket = ticket;
    }
}
